package com.gxlevi.prototype;

import sun.misc.ObjectInputFilter;

import java.io.*;

public class SheepDemo {
    public static void main(String[] args) {
        Milk milk = new Milk("完达山");
        Sheep sheep = new Sheep();
        sheep.setMilk(milk);
        sheep.setName("暖羊羊");
        Sheep sheep1 = sheep.deepClone();
        Sheep sheep2 = sheep.deepClone();

        System.out.println(sheep.getMilk().hashCode());
        System.out.println(sheep1.getMilk().hashCode());
        System.out.println(sheep2.getMilk().hashCode());
    }
}

class Sheep implements Cloneable, Serializable {
    private String name;
    private Milk milk;

    public Sheep deepClone() {
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;

        try {
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(this);

            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);

            Sheep sheep = (Sheep) ois.readObject();
            return sheep;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                bos.close();
                bis.close();
                oos.close();
                ois.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public Milk getMilk() {
        return milk;
    }

    public void setMilk(Milk milk) {
        this.milk = milk;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

class Milk implements Serializable {
    private String type;

    public Milk(String type) {
        this.type = type;
    }
}